<template>
    <view>
        <image class="home_bg" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homepg.png"></image>
        <home-search-nav @goSearch="goSearch"></home-search-nav>
        <view class="home_ad">
            <u-swiper
                keyName="picAbsolute"
                bgColor="#f6f6f6"
                height="240"
                radius="20"
                :list="adList"
                autoplay="false"
                indicatorMode="line"
                @change="adChangeEvent"
                @click="adEvent"
                circular="true"
            >
                <view slot="indicator" class="indicator">
                    <view
                        class="indicator__dot"
                        v-for="(item, index) in adList"
                        :key="index"
                        :class="[index === current && 'indicator__dot--active']"
                    ></view>
                </view>
            </u-swiper>
        </view>
        <home-menu @goToCookbook="goToCookbook()"></home-menu>
        <view class="home_total_weight_view">
            <view class="total_title">累积减重</view>
            <view style="margin-left: 42rpx; display: flex; flex-direction: column">
                <label style="color: #999999; font-size: 24rpx">平台累计减重量：</label>
                <label style="font-weight: bold; color: #333333; font-size: 40rpx; line-height: 48rpx"
                    >{{ weightLossTotal }}kg</label
                >
            </view>
        </view>

        <home-user-data
            v-if="userDetail.completeStatus == 1 && isLogin"
            @showImage="showShareImage()"
            @updateData="requestNewestWeight"
            :weightData="newestWeightData"
            @showSaveImage="showSaveImage()"
        />
        <home-go-information @goToInformation="goToInformation" v-else-if="userDetail.completeStatus != 1 && isLogin">
        </home-go-information>
        <weight_success_pop :show="isShowIntegral" @close="closeSuccess()" :integral="integral"></weight_success_pop>

        <share-img-pop-view
            v-if="isShowShareImg"
            :recordDate="newestWeightData.recordDate"
            :mainData="userDetail"
            :show="isShowShareImg"
            @close="close1"
            @saveImage="saveImage"
            :measurementRecordSharePicture="measurementRecordSharePicture"
            @shareMenu="shareMenu"
        ></share-img-pop-view>
        <save-img-pop-view
            v-if="isShowSaveImg"
            :mainData="newestWeightData"
            :show="isShowSaveImg"
            @close="closeSaveImg"
            @saveImage="saveImage"
        ></save-img-pop-view>

        <xunzhang-pop-view :list="xunzhangList" :show="isShowXunZhang" @close="isShowXunZhang = false">
        </xunzhang-pop-view>
        <ad-pop-view :mainData="adData" :show="showAd" @close="showAd = false" @goToAd="goToAd"></ad-pop-view>
    </view>
</template>
<!-- @shareMenu='shareMenu' -->
<script>
import { mapState, mapMutations } from "vuex";
import common from "@/common/common.js";
export default {
    data() {
        return {
            adList: [],
            isShowIntegral: false,
            score: "",
            isShowShareImg: false,
            isShowSaveImg: false,
            isShowXunZhang: false,
            xunzhangList: [],
            userDetail: {},
            newestWeightData: {},
            code: "",
            bindDeviceList: [],
            currentDevice: {},
            adData: {},
            showAd: false,
            isFirstLoad: false,
            weightLossTotal: 0,
            current: 0,
            integral: 0,
            measurementRecordSharePicture: "",
            weightUploading: 0,
            resistanceUploading: 0,
            requestNew: false,
        };
    },
    computed: {
        ...mapState(["isLogin", "userInfo"]),
    },
    watch: {},
    onShow() {
        if (this.isLogin) {
            this.requestNewestWeight();
            this.requestUser();
        }
        if (this.isFirstLoad == false) {
            this.requestPopAd();
        }
        uni.$once("uploadWeightSuccess", (item) => {
            if (item.score.score > 0) {
                this.isShowIntegral = true;
                this.score = item.score.score;
            }
            this.xunzhangList = [];
            this.xunzhangList.length = 0;
            if (item.medalData.length > 0) {
                item.medalData.forEach((itemMedal) => {
                    if (itemMedal.name != "" && itemMedal.name) {
                        const xunzhang = this.xunzhangList.find((v) => v.name == itemMedal.name);
                        if (!xunzhang) {
                            this.xunzhangList.push(itemMedal);
                        }
                    }
                });
                if (item.score.score == 0) {
                    this.isShowXunZhang = true;
                }
            }
        });
        this.requestWeightLossAll();
        this.requestAd();
        this.godailyWeight();
    },
    onLoad() {
        if (this.isLogin == false) {
            uni.login({
                provider: "weixin",
                success: (res) => {
                    this.code = res.code;
                    this.authCode();
                },
            });
        }
        this.isFirstLoad = true;
        this.requestPopAd();
    },
    methods: {
        ...mapMutations(["loginSaveUserInfo", "logout"]),
        close1() {
            this.isShowShareImg = false;
            uni.showTabBar();
        },
        closeSuccess() {
            this.isShowIntegral = false;
            if (this.xunzhangList.length > 0) {
                this.isShowXunZhang = true;
            }
        },
        closeSaveImg() {
            this.isShowSaveImg = false;
            uni.showTabBar();
        },

        goToInformation() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            uni.navigateTo({
                url: "/packageMine/pages/userinfo/userinfo",
            });
        },
        godailyWeight() {
            this.request
                .httpTokenJsonRequest("/mp-api/wx/home/search/dailyWeight/default", null, "POST", true)
                .then((res) => {
                    if (res.code == 0) {
                        this.integral = res.data.dailyWeight;
                        this.measurementRecordSharePicture = this.request.baseUrl + res.data.loseWeightSharePicture;
                    }
                });
        },
        saveImage(image) {
            let that = this;
            uni.saveImageToPhotosAlbum({
                filePath: image, //图片文件路径
                success: function () {
                    uni.showToast({
                        title: "图片保存成功",
                        icon: "none",
                    });
                    setTimeout(() => {
                        that.isShowSaveImg = false;
                        that.isShowShareImg = false;
                        uni.showTabBar();
                    }, 1000);
                },
                fail: function (e) {
                    uni.openSetting();
                    if (e.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
                        uni.showToast({
                            title: "请授权图片保存到相册",
                            icon: "none",
                        });
                    } else {
                        uni.showToast({
                            title: "图片保存失败",
                            icon: "none",
                        });
                    }
                },
            });
        },
        showShareImage() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            this.$nextTick(function () {
                // setTimeout(function(){
                this.isShowShareImg = true;
                // },1000)
                uni.hideTabBar();
            });
        },
        showSaveImage() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }

            this.isShowSaveImg = true;
            // uni.hideTabBar()
        },
        isAuthNicknamePhone() {
            if (this.userInfo.nickname == "" || this.userInfo.nickname == null || this.userInfo.nickname == undefined) {
                this.authUserInfo();
                return false;
            }
            if (this.userInfo.phone == "" || this.userInfo.phone == null || this.userInfo.phone == undefined) {
                uni.navigateTo({
                    url: "/pages/login/login",
                });
                return false;
            }
            return true;
        },
        authUserInfo() {
            uni.getUserProfile({
                desc: "Wexin",
                success: (res) => {
                    let avatar = res.userInfo.avatarUrl;
                    let nickname = res.userInfo.nickName;
                    this.sendUserInfo(avatar, nickname);
                },
            });
        },
        sendUserInfo(avatar, nickname) {
            var postData = {};
            postData.uid = this.userInfo.uid;
            postData.avatar = avatar;
            postData.nickname = nickname;
            this.request.httpTokenJsonRequest("/mp-api/wx/user/update", postData, "POST", false).then((res) => {
                if (res.code == 0) {
                    if (res.data.phone == "" || res.data.phone == null || res.data.phone == undefined) {
                        uni.navigateTo({
                            url: "/pages/login/login",
                        });
                    }
                    this.requestUser();
                }
            });
        },
        authCode() {
            var data = {};
            data.code = this.code;
            this.request.httpJsonRequest("/mp-api/wx/auth/code", data, "POST", false).then((res) => {
                if (res.code == 0) {
                    if (res.data != null) {
                        if (res.data.uid != 0) {
                            this.request.setToken(res.data.accessToken);
                            this.loginSaveUserInfo(res.data);
                            this.requestNewestWeight();
                            this.requestUser();
                        }
                    }
                }
            });
        },
        requestNewestWeight() {
            if (this.requestNew) {
                return;
            }
            this.requestNew = true;
            this.request
                .httpTokenRequest("/mp-api/wx/weight/newest", null, "POST")
                .then((res) => {
                    if (res.code == 0) {
                        if (res.data != "") {
                            res.data.fatDegreeName = res.data.fatDegreeName ? res.data.fatDegreeName : "正常";
                            this.newestWeightData = Object.assign({}, this.newestWeightData, res.data);
                        }
                    }
                    this.requestNew = false;
                })
                .catch(() => {
                    this.requestNew = false;
                });
        },
        requestUser() {
            this.request
                .httpTokenRequest(`/mp-api/wx/user/detail/${this.userInfo.uid}`, null, "POST", true)
                .then((res) => {
                    if (res.code == 0) {
                        this.loginSaveUserInfo(res.data);
                        this.userDetail = res.data;

                        this.newestWeightData.avatarAbsolute = this.userDetail.avatarAbsolute;
                        this.newestWeightData.nickname = this.userDetail.nickname;
                    }
                });
        },
        goSearch() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            uni.navigateTo({
                url: "/packageHome/pages/search/search",
            });
        },
        requestAd() {
            this.request.httpTokenRequest("/mp-api/wx/config/banner", null, "POST", true).then((res) => {
                if (res.code == 0) {
                    this.adList = res.data;
                    // res.data.forEach( item=> {
                    // 	this.adList.push(item)
                    // })
                }
            });
        },
        requestPopAd() {
            this.request.httpTokenRequest("/mp-api/wx/config/pop", null, "POST", true).then((res) => {
                if (res.code == 0) {
                    if (res.data.length > 0) {
                        this.adData = res.data[0];
                        if (this.adData.popRate == 0 || this.adData.popRate == 1) {
                            if (this.isFirstLoad) {
                                this.showAd = true;
                            }
                        } else if (this.adData.popRate == 2) {
                            this.showAd = true;
                        }
                        this.isFirstLoad = false;
                    }
                }
            });
        },
        goToAd() {
            if (this.isAuthNicknamePhone() == false) {
                this.showAd = false;
                return;
            }
            this.showAd = false;
            if (this.adData.jumpType == 0) {
                if (this.adData.jumpContent) {
                    uni.navigateTo({
                        url: this.adData.jumpContent,
                    });
                }
            } else if (this.adData.jumpType == 1) {
                uni.navigateTo({
                    url: `/packageHome/pages/adwebview/adwebview?url=${this.adData.jumpContent}`,
                });
            }
        },
        adEvent(index) {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            if (this.adList[index].jumpType == 0) {
                if (this.adList[index].jumpContent) {
                    uni.navigateTo({
                        url: this.adList[index].jumpContent,
                    });
                }
            } else if (this.adList[index].jumpType == 1) {
                uni.navigateTo({
                    url: `/packageHome/pages/adwebview/adwebview?url=${this.adList[index].jumpContent}`,
                });
            }
        },
        shareMenu(e) {
            this.anvasImages = e;
            this.close1();
        },
        adChangeEvent(e) {
            this.current = e.current;
        },
        goToCookbook() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            uni.navigateTo({
                url: "/packageHome/pages/cookbook/cookbook",
            });
        },
        requestWeightLossAll() {
            this.request.httpRequest("/mp-api/wx/home/weightLoss", null, "POST", true).then((res) => {
                if (res.code == 0) {
                    this.weightLossTotal = res.data;
                }
            });
        },
    },
    onShareAppMessage(res) {
        let that = this;
        let imageUrl =
            "https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/profile/upload/2024/06/04/5d2ad4dd-81c9-4056-8a4a-92b9c19a633a.jpg";
        if (res.from === "button") {
            imageUrl = that.anvasImages;
        }
        return {
            title: "倾小瘦小程序    您的随身身材管理顾问",
            imageUrl,
            path: "/pages/home/home",
            success(res) {
                uni.showToast({
                    title: "分享成功",
                    icon: "none",
                });
                that.isShowShareImg = false;
            },
            fail(res) {
                uni.showToast({
                    title: "分享失败",
                    icon: "none",
                });
                that.isShowShareImg = false;
            },
        };
    },
    onShareTimeline(res) {
        let that = this;
        let imageUrl =
            "https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/profile/upload/2024/06/04/5d2ad4dd-81c9-4056-8a4a-92b9c19a633a.jpg";
        if (res.from == "button") {
            imageUrl = that.anvasImages;
        }
        return {
            title: "倾小瘦小程序    您的随身身材管理顾问",
            imageUrl,
            path: "/pages/home/home",
            success(res) {
                uni.showToast({
                    title: "分享成功",
                    icon: "none",
                });
                that.isShowShareImg = false;
            },
            fail(res) {
                uni.showToast({
                    title: "分享失败",
                    icon: "none",
                });
                that.isShowShareImg = false;
            },
        };
    },
};
</script>

<style>
.home_bg {
    position: absolute;
    width: 100%;
    height: 1086rpx;
    top: auto;
    bottom: -166rpx;
    z-index: -1;
}

.home_ad {
    margin-top: 30rpx;
    margin-left: 30rpx;
    width: calc(100% - 60rpx);
    height: 240rpx;
    border-radius: 20rpx;
}

.home_total_weight_view {
    display: flex;
    flex-direction: row;
    background-image: url("https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homeljb.png");
    background-size: cover;
    margin-left: 30rpx;
    width: calc(100% - 60rpx);
    height: 120rpx;
    align-items: center;
    margin-top: -20px;
}

.total_title {
    width: 60rpx;
    height: 78rpx;
    font-size: 30rpx;
    margin-left: 30rpx;
    color: #234941;
    line-height: 39rpx;
    text-align: center;
}
</style>
